package com.app.brilliant.util;

import javafx.util.Pair;

import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;

public class WeightRandom<K, V extends Number> {

    private TreeMap<Double, K> weightMap = new TreeMap<>();

    public WeightRandom(List<Pair<K, V>> list) {
        for (Pair<K, V> pair : list) {
            double lastWeight = this.weightMap.size() == 0 ? 0 : this.weightMap.lastKey();//统一转为double
            System.out.println(lastWeight);
            this.weightMap.put(pair.getValue().doubleValue() + lastWeight, pair.getKey());//权重累加
        }
    }

    public K random() {
        double randomWeight = this.weightMap.lastKey() * Math.random();
        NavigableMap<Double, K> tailMap = this.weightMap.tailMap(randomWeight, false);
        //tailMap.pollFirstEntry();
        return this.weightMap.get(tailMap.firstKey());
    }

    public static void main(String[] args) {
        List<Pair<String, Double>> c = new ArrayList<>();
        c.add(new Pair<>("3", 3.));
        c.add(new Pair<>("2", 2.));
        c.add(new Pair<>("1", 1.));

        WeightRandom<String, Double> stringDoubleWeightRandom = new WeightRandom<>(c);
        for (int i = 0; i< 10 ; i ++) {
            String random = stringDoubleWeightRandom.random();
            System.out.println(random);
        }

    }

}